﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.UI.WebControls;
using Tizer.Core;
using Tizer.Core.DTO;
using Tizer.Core.Repository;
using Tizer.Web.Backoffice.Controls;
using Tizer.Web.Helper;

namespace Tizer.Web.Backoffice
{
    /// <summary>
    /// Добавление услуги
    /// </summary>
    public partial class ServiceEdit : AdminBasePage
    {
        /// <summary>
        /// Инициализация страницы
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Init(object sender, EventArgs e)
        {
            BindServiceTypeList();
            BindServiceParentList();
        }

        /// <summary>
        /// Загрузка страницы
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
            this.SetPageTitle();
            if (!Page.IsPostBack)
            {
                var id = QueryHelper.Value<int>("id", 0);
                if (id == 0)
                    Response.Redirect(UrlAdminDashboard);
                else
                {
                    using (var serviceRepository = new ServiceRepository())
                    {
                        var service = serviceRepository.GetById(id);
                        if (service != null)
                        {
                            txtName.Text = service.Name;
                            
                            if (service.ParentID != null)
                                ddlServiceParent.SelectedValue = service.ParentID.ToString();
                            else
                                ddlServiceParent.SelectedIndex = 0;

                            if (service.ServiceTypes != null)
                            {
                                var firstOrDefault = service.ServiceTypes.FirstOrDefault();
                                if (firstOrDefault != null)
                                    ddlServiceType.SelectedValue = firstOrDefault.ID.ToString();
                                else
                                    ddlServiceType.SelectedIndex = 0;
                            }
                            else
                                ddlServiceParent.SelectedIndex = 0;
                        }
                        else
                            Response.Redirect(UrlAdminDashboard);
                    }
                }
            }
        }

        /// <summary>
        /// Добавить услугу
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Edit (object sender, EventArgs e)
        {
            if (Page.IsPostBack && Page.IsValid)
            {
                if (!string.IsNullOrEmpty(txtName.Text))
                {
                    using (var serviceRepository = new ServiceRepository())
                    {
                        var service = new Service();

                        service.Name = txtName.Text;
                        service.IsPublished = chkActive.Checked;

                        if (ddlServiceParent.SelectedItem.Value != "0")
                            service.ParentID = Convert.ToInt32(ddlServiceParent.SelectedItem.Value);

                        if (ddlServiceType.SelectedItem.Value != "0")
                        {
                            using (var serviceTypeRepository = new ServiceTypeRepository(serviceRepository.Context))
                            {
                                ServiceType serviceType = serviceTypeRepository.GetById(Convert.ToInt32(ddlServiceType.SelectedItem.Value));
                                if (serviceType != null)
                                {
                                    service.ServiceTypes.Add(serviceType);
                                }
                            }
                        }

                        serviceRepository.Add(service);
                        serviceRepository.SaveChanges();
                        Response.Redirect(UrlAdminServiceList);
                    }
                }
            }
                tizerMessage.SetMessage("Ошибка", "Невозможно изменить услугу", MessageType.Error);
        }

        /// <summary>
        /// Заполнение списка типов услуг
        /// </summary>
        private void BindServiceTypeList()
        {
            ddlServiceType.Items.Clear();
            var emptyItem = new ListItem { Text = StrNotChoosed, Value = "0" };
            ddlServiceType.Items.Add(emptyItem);

            using (var serviceTypeRepository = new ServiceTypeRepository())
            {
                var serviceTypes = serviceTypeRepository.GetAll();
                if (serviceTypes != null)
                {
                    foreach (var serviceType in serviceTypes)
                    {
                        var item = new ListItem { Text = serviceType.Name, Value = serviceType.ID.ToString() };
                        ddlServiceType.Items.Add(item);
                    }
                }
            }
        }

        /// <summary>
        /// Заполнение списка родительских сервисов
        /// </summary>
        private void BindServiceParentList()
        {
            ddlServiceParent.Items.Clear();
            var emptyItem = new ListItem { Text = "- ", Value = "0" };
            ddlServiceParent.Items.Add(emptyItem);

            List<ServiceDTO> itemCollection = new List<ServiceDTO>();
            List<ListItem> groupCollection = new List<ListItem>();

            using (var serviceRepository = new ServiceRepository())
            {
                var services = serviceRepository.GetAll();
                if (services != null)
                {
                    foreach (var service in services)
                    {
                        var item = new ServiceDTO { Name = service.Name, Id = service.ID};
                        if (service.ParentID == null)
                        {
                            item.ParentId = 0;
                        }
                        else
                        {
                            item.ParentId = (int)service.ParentID;
                        }

                        var group = new ListItem();

                        if (service.ParentID != null)
                        {
                            group.Value = service.ParentID.ToString();
                            group.Text = service.Parent.Name;
                        }
                        else
                        {
                            group.Value = "0";
                            group.Text = "Корневые услуги";
                        }

                        if (groupCollection.Find(x => x.Text == group.Text) == null)
                            groupCollection.Add(group);

                        itemCollection.Add(item);
                    }

                    foreach (ListItem group in groupCollection)
                    {
                        List<ServiceDTO> serviceDtos = itemCollection.FindAll(x => x.ParentId.ToString() == group.Value);
                        foreach (ServiceDTO item in serviceDtos)
                        {
                            ListItem ddlItem = new ListItem();
                            ddlItem.Value = item.Id.ToString();
                            ddlItem.Text = item.Name;
                            ddlItem.Attributes["OptionGroup"] = group.Text;
                            ddlServiceParent.Items.Add(ddlItem);
                        }
                    }

                }
            }
            
        }

    }

}